<?php
namespace app\common\client;

use think\facade\Config;
use app\common\request\Curl;
use think\facade\Log;

class CheckIotClient {

        protected $userName = '';                                     //用户名
        protected $ip = '';                                                  //请求的ip
        protected $timeStamp = 0;                                  //请求的毫秒时间戳
        protected $key = '';                                              //系统id对应的密钥
        protected $sign = '';                                            //签名
        protected $seqId = '';                                       //请求id（唯一值）
        protected $httpHeaders = [];      //请求头
        
        /**
         * @function    构造方法
         * @param null
         * @return object
         */
        public function __construct()
        {
            $this->init();
        }
      
        
        /**
         * @function 初始化
         * @param $user_name
         * @param $key
         * @return null
         */
        private function init()
        {
            $this->ip = Config::get('iot.ip');
            $this->userName = Config::get('iot.userName');
            $this->key = Config::get('iot.password');
            $this->timeStamp = time() * 1000;
            $this->seqId = $this->createSeqId();
            $this->sign = $this->createSign();
            $this->httpHeaders = $this->headers();
        }
        
        /**
         * 心跳检测
         * @return boolean|mixed
         */
        public function heartCheck($url){
            $url = $url.'/checkHeartbeat';
            return $this->post($url,[]);
        }
        
        /**
         * iot客户端
         * @return boolean|mixed
         */
        public function testIotClient($url){
            $url = $url.'/checkIotClinet';
            $data = [];
            $data['token'] = "f30173557ee54d6e9c60857ee30889a2";
            return $this->post($url,$data);
        }
        
        /**
         * 测试redis连接
         * @return boolean|mixed
         */
        public function testRedis($url){
            $url = $url.'/checkRedis';
            $data = [];
            $data['token'] = "f30173557ee54d6e9c60857ee30889a2";
            return $this->post($url,$data);
        }
        
        /**
         * 测试mongo连接
         * @return boolean|mixed
         */
        public function testMongo($url){
            $url = $url.'/checkMongo';
            $data = [];
            $data['token'] = "f30173557ee54d6e9c60857ee30889a2";
            return $this->post($url,$data);
        }
        
        
        /**
         * @function    post方法
         * @param $url
         * @param $data
         */
        public function post($url,$data)
        {
            
            $curl = new Curl;
            $curl->set('CURLOPT_HTTPHEADER',$this->httpHeaders)->post($data)->url($url);
            
            if ($curl->error()) {
                
                Log::record('[ 请求错误 ] '.$curl->message(),'error');
                return false;
            } else {
                
                $info = $curl->info();
                
                if($info['http_code'] == 200){
                    $arr = json_decode($curl->data(),true);
                    if($arr !== null){
                        return $arr;
                    }else{
                        Log::record('[ 解码失败 ] '.$curl->data(),'error');
                        return false;
                    }
                }else{
                    Log::record('[ 请求目标 ] '.$curl->data() .$info['http_code'],'error');
                    return false;
                }
            }
        }
        
        /**
         * @function    创建请求id（不可重复）
         * @param null
         * @return string
         */
        private function createSeqId()
        {
            $charid = strtoupper(md5(uniqid(mt_rand(), true)));
            $hyphen = chr(45);// "-"
            $uuid = chr(123)// "{"
            .substr($charid, 0, 8).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen
            .substr($charid,16, 4).$hyphen
            .substr($charid,20,12)
            .chr(125);// "}"
            $uuid = str_replace(array('{','}','-'),array('','',''),$uuid);
            return $uuid;
        }
        
        /**
         * @function 生成签名
         * @param
         * @return null
         */
        private function createSign()
        {
            $string = '';                                               //第一步：对参数按照key=value的格式，并按照参数名ASCII字典序排序如下
            $string.= "user_name=".$this->userName;
            $string.= "&ip=".$this->ip;
            $string.= "&time_stamp=".$this->timeStamp;
            $string.= "&seq_id=".$this->seqId;
            $string.= "&key=".$this->key;                             //第二步：拼接API密钥
            return strtoupper(md5($string));                           //第三部：md5加密，并转化为大写
        }
        
        
        /**
         * @function    创建请求头信息
         * @param $system_name
         */
        private function headers()
        {
            $headers = [];
            $headers[] = 'User-Name:'.$this->userName;
            $headers[] = 'Ip:'.$this->ip;
            $headers[] = 'Time-Stamp:'.$this->timeStamp;
            $headers[] = 'Seq-Id:'.$this->seqId;
            $headers[] = 'Sign:'.$this->sign;
            return $headers;
        }
        
}